package com.rem.concurrency.multithreading.use;

import lombok.Data;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;

/**
 * 单次的生产与消费
 *
 * @author Rem
 * @date 2021-03-05
 */


public class ThreadAssist {
    static String goods;

    public static void main(String[] args) {
        Product product = new Product();
        Consumer consumer = new Consumer();

        new Thread(product).start();
        new Thread(consumer).start();
    }

}

class Product implements Runnable {
    @SneakyThrows
    @Override
    public void run() {
        if (StringUtils.isBlank(ThreadAssist.goods)) {
            ThreadAssist.goods = "chicken";
            System.err.println("生产鸡肉");
            Thread.sleep(1000);
        }
    }
}

@Data
class Consumer implements Runnable {

    private String myGooods;

    @SneakyThrows
    @Override
    public void run() {
        while (true) {
            if (StringUtils.isNotBlank(ThreadAssist.goods)) {
                myGooods = ThreadAssist.goods;
                ThreadAssist.goods = null;
                System.err.println("消费鸡肉");
                Thread.sleep(1000);
            }

            if (StringUtils.isNotBlank(myGooods)) {
                return;
            }
        }
    }
}
